<template>
  <ThreeBox ref="container"></ThreeBox>
</template>

<script setup>
import ThreeBox from "../../components/ThreeBox.vue";
import { ref, onMounted } from "vue";
import * as THREE from "three";
import { FBXLoader } from "../../lib/three/loaders/FBXLoader";
import { OrbitControls } from "../../lib/three/controls/OrbitControls";

const container = ref(null);
let threeBox = null;
let threePara = null;
let scene = new THREE.Scene();

function animate() {
  requestAnimationFrame(animate);
  render();
}

function render() {
  threePara.renderer.render(scene, threePara.camera);
}

function init() {
  //环境光
  let ambientLight = new THREE.AmbientLight(0xffffff, 0.2);
  scene.add(ambientLight);

  //环境纹理
  let loaderTexture = new THREE.CubeTextureLoader();
  loaderTexture.setPath("./three/skybox/Park2/");
  let textureEnvMap = loaderTexture.load([
    "posx.jpg",
    "negx.jpg",
    "posy.jpg",
    "negy.jpg",
    "posz.jpg",
    "negz.jpg",
  ]);

  //加载模型
  let loaderFbx = new FBXLoader();
  loaderFbx.load(
    import.meta.env.VITE_APP_TOMCAT + "/cesium/largemodel/管道组.fbx",
    (object) => {
      object.traverse((child) => {
        if (child.isMesh) {
          child.castShadow = true;
          child.receiveShadow = true;

          if (child.material instanceof THREE.MeshLambertMaterial) {
            /* let basicMaterial = new THREE.MeshBasicMaterial({
              color: child.material.color,
            });
            basicMaterial.map = child.material.map;
            child.material = basicMaterial; */
            child.material.map.encoding = THREE.LinearEncoding;
          } else {
            child.material.envMap = textureEnvMap;
          }
        }
      });
      scene.add(object);
    }
  );

  //相机
  threePara.camera = new THREE.PerspectiveCamera(
    45,
    threeBox.clientWidth / threeBox.clientHeight,
    0.1,
    1000
  );
  threePara.camera.position.set(300, 300, 300);
  threePara.camera.lookAt(0, 0, 0);

  //渲染器
  threePara.renderer = new THREE.WebGLRenderer({ alpha: true });
  threePara.renderer.setPixelRatio(window.devicePixelRatio);
  threePara.renderer.setSize(threeBox.clientWidth, threeBox.clientHeight);
  threeBox.appendChild(threePara.renderer.domElement);

  //控制器
  new OrbitControls(threePara.camera, threePara.renderer.domElement);
}

onMounted(() => {
  threeBox = container.value.threeBox;
  threePara = container.value.threePara;
  init();
  animate();
});
</script>
